package com.stud.common.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.stud.common.core.domain.entity.SysDictData;
import com.stud.common.core.redis.RedisCache;
import com.stud.common.exception.ServiceException;
import com.stud.common.utils.spring.SpringUtils;

import java.util.*;

/**
 * @author sdx
 * @title
 * @desription
 * @data 2023-02-16 10:25
 */
public class WeChatUtil {
    private static String accessTokenCache;
    private static RedisCache redisCache = SpringUtils.getBean("redisCache");
    private static String APPID = "wxb0f10ed7eb9b7da5";
    private static String SECRET = "1a701298f2663cfb464e5fbfd006b947";
    private static String GRANT_TYPE = "client_credential";

    /**
     * 获取小程序token
     *
     * @return
     */
    public static String getWeChatAppAccessToken() {
        Map<String, Object> map = new HashMap<>();
        map.put("appid", APPID);
        map.put("secret", SECRET);
        map.put("grant_type", GRANT_TYPE);
        String result = HttpRequest
                .get("https://api.weixin.qq.com/cgi-bin/token")
                .form(map)
                .execute().body();
        JSONObject jsonObject = JSONObject.parseObject(result);
        String accessToken = jsonObject.getString("access_token");
        if (accessToken == null) {
            throw new ServiceException("获取accessToken失败,错误码为:" + jsonObject.getString("errcode"));
        }
        redisCache.setCacheObject("wechat_access_token", accessToken);
        redisCache.expire("wechat_access_token", jsonObject.getLong("expires_in") - 100);
        return accessToken;
    }

    /**
     * 获取小程序OpenPid
     *
     * @param code
     * @return
     */
    public static Map<String, Object> getPluginOpenPid(String code) {
        accessTokenCache = redisCache.getCacheObject("wechat_access_token");
        if (accessTokenCache == null) {
            // 如果缓存中没有 accessToken，则重新获取
            accessTokenCache = getWeChatAppAccessToken();
        }
        String url = "https://api.weixin.qq.com/wxa/getpluginopenpid?access_token=" + accessTokenCache;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", code);
        String jsonString = jsonObject.toJSONString();
        String result = HttpRequest.post(url)
                .body(jsonString).execute().body();
        return JSON.parseObject(result, new TypeReference<Map<String, Object>>() {
        });
    }

    /**
     * @param code 登录时获取的 code
     * @return { session_key 会话密钥 unionid 用户在开放平台的唯一标识符 errmsg 错误信息 openid 用户唯一标识 errcode 错误码 }
     */
    public static Map<String, Object> code2Session(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=%1$s&secret=%2$s&js_code=%3$s&grant_type=authorization_code";
        url = String.format(url, APPID, SECRET, code);
        String result = HttpRequest.get(url).execute().body();
        return JSON.parseObject(result, new TypeReference<Map<String, Object>>() {
        });
    }


}
